<?php
namespace app\common\keloop;


use app\admin\model\Shop;
use app\admin\model\shop\Order;
use app\common\controller\Backendj;
use app\models\common\Config;
use think\Log;
use think\Model;

class Delivery extends Backendj
{

    /**
     * @param $order
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 创建订单
     */
    public static function addKeloopOrder($order)
    {

        $store= (new Shop())->where('id',$order['shop_id'])->find();
        try {
            // 封装参数
            $param = [
                'shop_id' =>  $store['id'],
                'shop_name' =>  $store['shop_name'],
                'shop_tel' => $store['phone'],
                'shop_address' => $store['address'],
                'shop_tag' => $store['lng'].','.$store['lat'],
                'order_content' => $order['guige'],//订单内容
//                'order_note' => $order['userNote'],//订单备注
//                'order_mark' => $order['takeNo'],//订单标识
                'order_from' => '第三方',//订单来源
                'order_time' => $order['order_time'],
                'note' => $order['order_number'],
                'customer_name' => $order['harvest_user'],
                'customer_tel' => $order['harvest_phone'],
                'customer_address' =>  $order['harvest_address'],
                'customer_tag' => $order['harvest_lng'].','.$order['harvest_lat'],
                'order_no' => $order['order_number'],
                'order_price' =>  $order['actual_price'], //订单总价格
                'order_origin_price' => $order['actual_price'], //订单原始价格
                'pay_status' => 0, //0已支付 1货到付款
                'pay_fee' => $order['distribution_price'],//订单原配送费
//                'pre_times' => $order['serviceTime']
            ];
            // 创建 SDK 实例
            $sdk = new KeloopSdk();
            // 调用 createOrder 方法
            $result = $sdk->createOrder($param);
            Log::log([
                '快跑者创建订单',
                'msg'=>$result
            ]);
            // 业务逻辑处理
            if (is_null($result)) {
                exit('创建订单失败');
            } else if (is_array($result)) {
                if ($result['code'] == 200) {
                    exit('success');
                } else {
                    exit('错误信息：' . $result['message']);
                }
            } else {
                exit('接口调用异常');
            }
        } catch (Exception $e) {
            exit('接口调用异常：' . $e->getMessage());
        }
    }

    //获取订单价格
    static function getOrderPrice($order, $config) {
        header("Content-type: text/html; charset=utf-8");
        $guid = str_replace('-', '', Uupt::guid());
        // $config = self::getUuptSet($order['storeId']);
        $store=(new \yii\db\Query())
            ->from('{{%ybwm_store}}')
            ->where('id=:id',[':id'=>$order['storeId']])->one();
        $city = $order['area'];
        $sellerZb = coordinateSwitchf($store['lat'], $store['lng']);
        $orderZb = coordinateSwitchf($order['lat'], $order['lng']);
        $url = $config['domain']."getorderprice.ashx";
        $data = [
            'origin_id' => $order['outTradeNo'],
            'from_address' => $store['address'],
            'to_address' => $order['receivedAddress'],
            'city_name' => $city,
            'to_lng' => $orderZb['Longitude'],
            'to_lat' => $orderZb['Latitude'],
            'from_lng' => $sellerZb['Longitude'],
            'from_lat' => $sellerZb['Latitude'],
            'nonce_str' => strtolower($guid),
            'timestamp' => time(),
            'appid' => $config['appid'],
            'openid' => $config['openid'],
            'send_type' => 0,
        ];
        ksort($data);
        $data['sign'] =  Uupt::sign($data, $config['appKey']);
        $res = Uupt::request_post($url, $data);
        //var_dump($res);die;
        return $res;
    }

    static function  addUuptOrder($order,$module){
        $config = self::getUuptSet($order['storeId'], $order['uniacid']);
        $priceInfo = json_decode(self::getOrderPrice($order, $config), true);
        if (!isset($priceInfo['price_token'])) {
            echo json_encode(['code'=>2,'msg'=>$priceInfo['return_msg']]);die;
            return $priceInfo['return_msg'];
        }
        header("Content-type: text/html; charset=utf-8");
        $guid = str_replace('-', '', Uupt::guid());
        $url = $config['domain']."addorder.ashx";
        if (Yii::$app->params['isDev'] == true) {
            $callBack = Yii::$app->request->hostInfo . '/addons/' . $module . '/index.php/channelApi/delivery-notice/uupt-notice';
        } else {
            $callBack = Yii::$app->request->hostInfo . '/index.php/channelApi/delivery-notice/uupt-notice';
        }
        $data = [
            'price_token' => $priceInfo['price_token'],
            'order_price' => $priceInfo['total_money'],
            'balance_paymoney' => $priceInfo['need_paymoney'],
            'receiver' => $order['receivedName'],
            'receiver_phone' => $order['receivedTel'],
            'note' => $order['takeNo'],
            'callback_url' =>$callBack,
            'push_type' => 0,
            'special_type' => 0,
            'callme_withtake' => 0,
            'nonce_str' => strtolower($guid),
            'timestamp' => time(),
            'appid' => $config['appid'],
            'openid' => $config['openid'],
        ];
        //var_dump($data);die;
        ksort($data);
        $data['sign'] = Uupt::sign($data, $config['appKey']);
        $res = Uupt::request_post($url, $data);
        $result=json_decode($res,true);
        /*if($result['return_code']=='ok'){
            return 'success';
        }else{
            return $result['return_msg'];
        }*/
        $result['otherFee']=$priceInfo['need_paymoney'];
        return $result;
    }

//取消订单
    static function cancelUuptOrder($order){
        header("Content-type: text/html; charset=utf-8");
        $guid = str_replace('-', '', Uupt::guid());
        $config = self::getUuptSet($order['storeId'],$order['uniacid']);
        $url = $config['domain']."cancelorder.ashx";
        $data = [
            'origin_id' => $order['outTradeNo'],
            'reason' =>'用户取消订单',
            'nonce_str' => strtolower($guid),
            'timestamp' => time(),
            'appid' =>$config['appid'],
            'openid' => $config['openid'],
        ];

        ksort($data);
        $data['sign'] = Uupt::sign($data,  $config['appKey']);
        //var_dump($data);die;
        $res = Uupt::request_post($url, $data);
        $result= json_decode($res, true);
        if($result['return_code']=='ok'){
            return 'success';
        }else{
            return $result['return_msg'];
        }
    }


    //订单配送信息
    static function otherInfo($order){
        $otherInfo=json_decode($order['otherInfo'],true);
        $status='待接单';
        if($order['deliveryMode']==2){//达达
            switch ($otherInfo['order_status']) {
                case 2:
                    $status = '待取货';
                    break;
                case 3:
                    $status = '配送中';
                    break;
                case 4:
                    $status = '已完成';
                    break;
                case 5:
                    $status = '已取消';
                    break;
                case 8:
                    $status = '指派单';
                    break;
                case 9:
                    $status = '妥投异常之物品返回中';
                    break;
                case 10:
                    $status = '妥投异常之物品返回完成';
                    break;
                case 100:
                    $status = '骑士到店';
                    break;
                case 1000:
                    $status = '创建达达运单失败';
                    break;

            }
            $arr['createTime'] = date('Y-m-d H:i:s', $otherInfo['update_time']);
            $arr['transporterName'] = $otherInfo['dm_name'];
            $arr['transporterPhone'] = $otherInfo['dm_mobile'];
            $arr['orderStatus'] =$status;
        }elseif ($order['deliveryMode']==4){
            switch ($otherInfo['status']) {
                case 'loading':
                    $status = '待付款';
                    break;
                case 'cancel':
                    $status = '订单已取消';
                    break;
                case 'payed':
                    $status = '待接单';
                    break;
                case 'accepted':
                    $status = '待取件';
                    break;
                case 'geted':
                    $status = '待收件';
                    break;
                case 'gotoed':
                    $status = '待评价';
                    break;
                case 'completed':
                    $status = '订单已完成';
                    break;

            }
            $arr['createTime'] = date('Y-m-d H:i:s', $otherInfo['time']);
            $arr['transporterName'] = $otherInfo['rider_name'];
            $arr['transporterPhone'] = $otherInfo['rider_mobile'];
            $arr['orderStatus'] =$status;
        }elseif ($order['deliveryMode']==5){
            switch ($otherInfo['order_status']) {
                case 1:
                    $status = '订单创建';
                    break;
                case 2:
                    $status = '订单取消';
                    break;
                case 10:
                    $status = '配送员确认订单';
                    break;
                case 12:
                    $status = '配送员到店';
                    break;
                case 15:
                    $status = '配送员配送中';
                    break;
                case 17:
                    $status = '订单完成';
                    break;
                case 28:
                    $status = '可疑单被据单';
                    break;

            }
            $arr['createTime'] = date('Y-m-d H:i:s', $otherInfo['push_time']);
            $arr['transporterName'] = $otherInfo['operator_name'];
            $arr['transporterPhone'] = $otherInfo['operator_phone'];
            $arr['lat'] = $otherInfo['courier']['rider_lat'];
            $arr['lng'] = $otherInfo['courier']['rider_lng'];
            $arr['orderStatus'] =$status;
        }elseif ($order['deliveryMode']==6){
            switch ($otherInfo['data']['order_status']) {
                case "1":
                    $statusMsg = '系统已接单';
                    break;
                case "20":
                    $statusMsg = '已分配骑手';
                    break;
                case "80":
                    $statusMsg = '骑手已到店';
                    break;
                case "2":
                    $statusMsg = '配送中';
                    break;
                case "3":
                    $statusMsg = '已送达';
                    break;
                case "5":
                    $statusMsg = '异常';
                    break;
                case "4":
                    $statusMsg = '已取消';
                    break;
                default:
                    $statusMsg = '待接单';
            }
            $arr['createTime'] = date('Y-m-d H:i:s', $order['createdAt']);
            $arr['statusMsg'] = $statusMsg;
            $arr['transporterName'] = $otherInfo['data']['carrier_driver_name'];
            $arr['supplierPhone'] = $otherInfo['data']['carrier_driver_phone'];
        }elseif ($order['deliveryMode']==7){

            $arr['createTime'] = date('Y-m-d H:i:s', $otherInfo['push_time']);
            $arr['transporterName'] = $otherInfo['courier']['name'];
            $arr['transporterPhone'] = $otherInfo['courier']['mobile'];
            $arr['lat'] = $otherInfo['courier']['latitude'];
            $arr['lng'] = $otherInfo['courier']['longitude'];
            $arr['orderStatus'] =$otherInfo['statusDesc'];
        }elseif($order['deliveryMode']==8){
            switch ($otherInfo['state']) {
                case 1:
                    $statusMsg = '下单成功';
                    break;
                case 3:
                    $statusMsg = '跑男抢单 ';
                    break;
                case 4:
                    $statusMsg = '已到达 ';
                    break;
                case 5:
                    $statusMsg = '已取件';
                    break;
                case 6:
                    $statusMsg = '到达目的地';
                    break;
                case 10:
                    $statusMsg = '收件人已收货';
                    break;
                case -1:
                    $statusMsg = '订单取消';
                    break;

            }
            $arr['transporterName'] = $otherInfo['driver_name'];
            $arr['supplierPhone'] = $otherInfo['driver_mobile'];
            $arr['statusMsg'] = $statusMsg;
        }elseif ($order['deliveryMode']==11){
            $arr['transporterName'] = $otherInfo['rider_name'];
            $arr['supplierPhone'] = $otherInfo['rider_phone'];
            $arr['statusMsg'] = $otherInfo['status_desc'];
        }
    }

    //配送订单
    static function addOrder($id, $type = null)
    {
        $order = (new \yii\db\Query())
            ->from('{{%ybwm_takeout_order}}')
            ->where('id=:id', [':id' => $id])->one();
        if ($type) {
            $order['deliveryMode'] = $type;
        }
        if ($order['deliveryMode'] == 2) {
            $result = self::addDataOrder($order, 'yb_wm');
            if ($result['error_code'] == 0) {
                Yii::$app->db->createCommand()->update('{{%ybwm_takeout_order}}',['otherFee'=>$result['fee'],'state'=>4], 'id=:id', ['id' =>$id])->execute();
            } else {
                return $result['error_msg'];
            }
        }elseif ($order['deliveryMode'] == 3) {
            $result = self::addDianwodaOrder($order);
            if ($result== 'success') {
                Yii::$app->db->createCommand()->update('{{%ybo2ov2_takeout_order}}',['makeOrder'=>$result['data']['order_number'],'state'=>4], 'id=:id', ['id' =>$id])->execute();
            } else {
                return $result['msg'];
            }

        }  elseif ($order['deliveryMode'] == 4) {
            $result = self::makeAddOrder($order, 'yb_wm');
            if ($result['error_code'] == 0) {
                Yii::$app->db->createCommand()->update('{{%ybwm_takeout_order}}',['makeOrder'=>$result['data']['order_number'],'state'=>4], 'id=:id', ['id' =>$id])->execute();
            } else {
                return $result['msg'];
            }

        } elseif ($order['deliveryMode'] == 5) {
            $result = self::sftcAddOrder($order);
            // var_dump($result);die;
            if ($result['error_code'] == 0) {
                Yii::$app->db->createCommand()->update('{{%ybwm_takeout_order}}',['sftcOrder'=>$result['result']['sf_order_id'],'state'=>4], 'id=:id', ['id' =>$id])->execute();
            } else {
                return $result['error_msg'];
            }

        }elseif ($order['deliveryMode'] == 6) {
            $result = self::addFengniaoOrder($order,'yb_wm');
            if ($result['code']=='200') {
                Yii::$app->db->createCommand()->update('{{%ybwm_takeout_order}}',['state'=>4], 'id=:id', ['id' =>$id])->execute();
            } else {
                return $result['msg'];
            }

        } elseif ($order['deliveryMode'] == 7) {
            $result = self::sanAddOrder($order);
            if ($result['status'] == 200) {
                $params['sanOrder'] = $result['data']['orderNumber'];
                $params['otherFee'] = $result['data']['totalFeeAfterSave'] / 100;
                $params['state']=4;
                Yii::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', $params, 'id=:id', ['id' => $order['id']])->execute();
            } else {
                return $result['msg'];
            }
        }elseif ($order['deliveryMode'] == 8) {
            $result = self::addUuptOrder($order,'yb_wm');
            if ($result['return_code']=='ok') {
                //$params['sanOrder'] = $result['data']['orderNumber'];
                $params['otherFee'] = $result['otherFee'];
                $params['state']=4;
                Yii::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', $params, 'id=:id', ['id' => $order['id']])->execute();
            } else {
                return $result['return_msg'];
            }
        }elseif ($order['deliveryMode'] == 9) {
            $result = self::yunBeiAddOrder($order,'yb_wm');
            //var_dump($result);die;
            if ($result['code']==1) {
                //$params['sanOrder'] = $result['data']['orderNumber'];
                $params['otherFee'] = $result['data']['money'];
                $params['state']=4;
                Yii::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', $params, 'id=:id', ['id' => $order['id']])->execute();
            } else {
                return $result['msg'];
            }
        }elseif ($order['deliveryMode'] == 11) {
            $result = self::MaiyatianAddOrder($order,'yb_wm');
            $result=json_decode($result,true);
            if ($result['status']==1) {
                //$params['sanOrder'] = $result['data']['orderNumber'];
                $params['otherFee'] = $result['data']['money'];
                $params['state']=4;
                Yii::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', $params, 'id=:id', ['id' => $order['id']])->execute();
            } else {
                return $result['msg'];
            }
        }
        return 'success';

    }

    //取消配送订单
    public function cancelOrder($id)
    {
        $order = (new \yii\db\Query())
            ->from('{{%ybwm_takeout_order}}')
            ->where('id=:id', [':id' => $id])->one();
        $result = 'success';
        if ($order['deliveryMode'] == 2) {
            $result = self::cancelDataOrder($order);
        }elseif ($order['deliveryMode'] == 4) {
            $result = self::makeCancelOrder($order);
        } elseif ($order['deliveryMode'] == 5) {
            $result = self::cancelShunfengOrder($order);
        } elseif ($order['deliveryMode'] == 6) {
            $result = self::CancelFengniaoOrder($order);
        }elseif ($order['deliveryMode'] == 7) {
            $result = self::cancelSanOrder($order);
        }elseif ($order['deliveryMode'] == 8) {
            $result = self::cancelUuptOrder($order);
        }elseif ($order['deliveryMode'] == 9) {
            $result = self::cancelYunBeiOrder($order);
        }elseif ($order['deliveryMode'] == 11) {
            $result = self::cancelMaiyatianOrder($id);
        }
        if ($result == 'success') {
            return true;
        } else {
            return $result;
        }
    }

   static function cancelMaiyatianOrder($orderId){
       $res=Maiyatian::orderAllCancel($orderId);
       $data=json_decode($res,true);
       if($data['status']==1){
           return 'success';
       }else{
           echo json_encode(['code'=>$data['status'],'msg'=>$data['msg']]);die;
       }
   }


    /**
     * @param $store
     * @return array
     * 获取达达配置
     */
    public static function getDadaSet($store = null)
    {
        $config['app_key'] = 'dadab3ab08bc11e7ecf';
        $config['app_secret'] = '82a796ce54741e245a9d250bd81daf21';
        $config['source_id'] = '609800';
        $config['shop_no'] = $store['shop_no']?:'ab581fcabe394eab';
        return $config;
    }

    /**
     * @param $order
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 达达创建订单
     */
    public static function addDadaOrder($order)
    {
        if(!$order['origin_mark_no']){
            $count = (new Order)->where('origin_mark_no','not null')->count();
            $count = $count+1;
            Order::update(['origin_mark_no'=>'#'.$count],['id'=>$order['id']]);
        }
        $store= (new Shop())->where('id',$order['shop_id'])->find();
        $config = self::getDadaSet($store);
        $callBack = request()->domain().'/api/wechat/orderDaDaNotifyx';
        try {
            // 封装参数
            $param = array(
                'shop_no' => $config['shop_no'], //门店编号
                'origin_id' => $order['order_number'], //订单id
                'tips' => 0, //小费
                'info' => $order['order_number'], //备注
                'cargo_weight' => 1,
                'cargo_price' => $order['actual_price'],
                'is_prepay' => 0,
                'receiver_name' => $order['harvest_user'],
                'receiver_address' => $order['harvest_address'],
                'receiver_phone' => $order['harvest_phone'],
                'receiver_lat' => $order['harvest_lat'],
                'receiver_lng' => $order['harvest_lng'],
                'callback' => $callBack,
            );
            $dada = new Base($config['app_key'],$config['app_secret'],$config['source_id']);
            $res = $dada->order->addOrder($param);
            if($res['code'] != 0){
                Log::log([
                    'msg'=>'订单派送到达达平台报错',
                    'res'=>$res
                ]);
            }
        } catch (Exception $e) {
            exit('接口调用异常：' . $e->getMessage());
        }
        return $res;
    }



    /**
     * @param $order
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 查询运费
     */
    public static function queryDadaFeeOrder($order)
    {
        $store= (new Shop())->where('id',$order['shop_id'])->find();
        $callBack = request()->domain().'/api/wechat/orderDaDaNotifyx';
        try {
            // 封装参数
            //609800-6356420
            //ab581fcabe394eab 测试门店号
            $param = array(
                'shop_no' => 'ab581fcabe394eab', //门店编号
                'origin_id' => $order['order_number'], //订单id
                'cargo_price' => $order['actual_price'],
                'is_prepay' => 0,
                'tips' => 0, //小费
                'info' => $order['order_number'], //备注
                'cargo_weight' => 1,
                'receiver_name' => $order['harvest_user'],
                'receiver_address' => $order['harvest_address'],
                'receiver_phone' => $order['harvest_phone'],
                'receiver_lat' => $order['harvest_lat'],
                'receiver_lng' => $order['harvest_lng'],
                'callback' => $callBack,
            );
            $dada = new Base();
            $res = $dada->order->queryDeliverFee($param);

        } catch (Exception $e) {
            exit('接口调用异常：' . $e->getMessage());
        }
        return $res;
    }



    public static function getOrderTrack($order_number)
    {
        try {
            // 封装参数
            $param = array(
                'order_id' => $order_number, //订单id
            );
            $dada = new Base();
            $res = $dada->order->orderTrack($param);
        } catch (Exception $e) {
            exit('接口调用异常：' . $e->getMessage());
        }
        return $res;
    }

    public static function getOrderTransporterPosition($order_number)
    {
        try {
            // 封装参数
            $param = array(
                'orderIds' => $order_number, //订单id
            );
            $dada = new Base();
            $res = $dada->order->orderTransporterPosition($param);
        } catch (Exception $e) {
            exit('接口调用异常：' . $e->getMessage());
        }
        return $res;
    }



}
